package Graphique;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.rmi.RemoteException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.*;
import Serveur.Twouit;
import Serveur.TwouitAvecImage;

import Client.Client;

public class Twouitter extends JFrame{
	private static final long serialVersionUID = 1L;

	private Client client;
	
	private JLabel intro = new JLabel("Twouitter");
	private JTextArea textTwouit = new JTextArea("Entrez votre twouit ici", 7, 5);
	
	private JButton twouitter = new JButton("Twitter");
	private JButton annuler = new JButton("Annuler"); 
	
	private JButton ajouterImage = new JButton("Ajouter une image");
	private JFileChooser fileChooser = new JFileChooser();
	private Twouit t;
	private ImageIcon ic;
	
	private JPanel jp;
	
	private ActionListenerChoix alc = new ActionListenerChoix();
	
	public Twouitter(Client client){
		
		super("Twouitter");
		
		this.setSize(500, 500);
		
		twouitter.addActionListener(alc);
		ajouterImage.addActionListener(alc);
		annuler.addActionListener(alc);
		
		jp = new JPanel();
		jp.setLayout(new GridLayout(5, 1));
		jp.add(intro);
		jp.add(textTwouit);
		jp.add(ajouterImage);
		jp.add(twouitter);
		jp.add(annuler);
		
		this.add(jp);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		this.pack();
		this.client = client;
		
	}
	
	private class ActionListenerChoix implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			Object obj = e.getSource();
			
			if(twouitter.equals(obj)){
				try {
					t = new TwouitAvecImage(textTwouit.getText(), getTopic(textTwouit.getText()), client.getUtilisateur(), ic);
					client.twouitter(t);
					dispose();
					
				} catch (RemoteException e1) {
					e1.printStackTrace();
				}
			}
			if(ajouterImage.equals(obj)){
				int returnVal = fileChooser.showOpenDialog(jp);
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					File file = fileChooser.getSelectedFile();
	
					ic = new ImageIcon(file.getAbsolutePath());
					System.out.println("Opening: " + file.getName() + ".\n");
				}
			}
			if(annuler.equals(obj)){
				dispose();
			}
		}
	}
	
    private static String getTopic(String twouit)
    {
        Pattern pattern = Pattern.compile("#(\\w+)");
        Matcher matcher = pattern.matcher(twouit);

        if (matcher.find())
            return matcher.group(1);
        else
            return "";
    }
}
